// pages/admin/admin.js
const api = require('../../utils/api.js')
const config = require('../../utils/config.js')
const util = require('../../utils/util.js')
const app = getApp()

Page({
    data: {
        orders: [],
        stats: {
            pending: 0,
            processing: 0,
            today: 0,
            total: 0
        },
        statusFilter: '',
        statusText: {
            pending: '待处理',
            processing: '处理中',
            completed: '已完成',
            rejected: '已拒绝'
        },
        statusClass: {
            pending: 'status-pending',
            processing: 'status-processing',
            completed: 'status-completed',
            rejected: 'status-rejected'
        },
        page: 1,
        hasMore: true,
        hasPermission: false,  // 是否有查看工单的权限
        isLoading: true // 新增：加载状态
    },

    onLoad() {
        if (typeof this.getTabBar === 'function' && this.getTabBar()) {
            this.getTabBar().setData({
                selected: 2
            })
        }
        // 检查权限（在onShow中检查，确保app.globalData已更新）
        this.checkPermission()
    },

    onShow() {
        // 检查权限（在onShow中检查，确保app.globalData已更新）
        this.checkPermission()
    },

    checkPermission() {
        const app = getApp()
        const userRole = app.globalData.userRole
        const isAdmin = app.globalData.isAdmin
        const hasPermission = isAdmin || userRole === 'admin' || userRole === 'teacher' || userRole === 'student'

        this.setData({
            hasPermission,
            isLoading: false
        })

        if (hasPermission) {
            this.loadStats()
            this.loadOrders()
        }
    },

    onReachBottom() {
        if (this.data.hasMore) {
            this.loadMore()
        }
    },

    onPullDownRefresh() {
        this.refreshOrders()
    },


    // 加载统计数据
    loadStats() {
        api.request({
            url: '/repair/stats',
            method: 'GET'
        }).then(res => {
            this.setData({
                stats: res
            })
        }).catch(err => {
            console.error('加载统计数据失败', err)
        })
    },

    // 加载工单列表
    loadOrders() {
        wx.showLoading({ title: '加载中...' })

        const params = {
            isAdmin: true,
            openid: app.globalData.openid,
            status: this.data.statusFilter,
            page: this.data.page,
            pageSize: config.pageSize
        }

        api.getRepairOrders(params).then(res => {
            const orders = res.list || res

            // 格式化时间
            orders.forEach(order => {
                order.created_at = util.relativeTime(util.safeDate(order.created_at).getTime())

                // 判断是否紧急（超过24小时未处理）
                const createTime = util.safeDate(order.created_at).getTime()
                const now = Date.now()
                order.isUrgent = (now - createTime > 24 * 60 * 60 * 1000) && order.status === 'pending'
            })

            this.setData({
                orders: this.data.page === 1 ? orders : [...this.data.orders, ...orders],
                hasMore: orders.length >= config.pageSize
            })
        }).catch(err => {
            console.error('加载工单列表失败', err)
        }).finally(() => {
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },

    // 刷新列表
    refreshOrders() {
        this.setData({
            page: 1,
            hasMore: true
        })
        this.loadStats()
        this.loadOrders()
    },

    // 加载更多
    loadMore() {
        this.setData({
            page: this.data.page + 1
        })
        this.loadOrders()
    },

    // 状态筛选
    filterByStatus(e) {
        const status = e.currentTarget.dataset.status

        this.setData({
            statusFilter: status,
            page: 1,
            hasMore: true
        })

        this.loadOrders()
    },

    // 处理工单
    handleOrder(e) {
        const orderId = e.currentTarget.dataset.id

        wx.navigateTo({
            url: `/pages/admin-detail/admin-detail?orderId=${orderId}`
        })
    },

    // 订阅新报修通知
    async handleSubscribe() {
        const subscribe = require('../../utils/subscribe.js')
        const res = await subscribe.requestAdminSubscribe()
        if (res) {
            wx.showToast({
                title: '订阅成功',
                icon: 'success'
            })
        }
    }
})
